package org.lanqiao.filter;


import com.alibaba.fastjson.JSON;
import org.lanqiao.common.ThreadLocalHandler;
import org.lanqiao.utils.Result;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器（检查用户是否登录）
 */
@WebFilter(filterName = "loginCheckFilter" , urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MACHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的URI地址
        String requestURI = request.getRequestURI();


        //定义不需要拦截的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/front/**",
                "/backend/**"
        };

        //判断本次请求路径是否需要处理
        boolean check = check(urls , requestURI);
        if(check){
            filterChain.doFilter(request , response);
            return;
        }

        //用户已经登陆
        if(request.getSession().getAttribute("employee") != null){
            Long id = (Long) request.getSession().getAttribute("employee");
            ThreadLocalHandler.setCurrentId(id);

            filterChain.doFilter(request , response);
            return;
        }

        //用户没有登录直接访问主界面
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }



    public boolean check(String[] urls , String requestURI){
        for (String url : urls) {
            boolean mach = PATH_MACHER.match(url , requestURI);
            if(mach){
                return true;
            }
        }
        return false;
    }
}
